package org.seefly.iprint.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 
 *  加密算法工具类
 * @author liujianxin
 * @date 2018年3月24日 下午8:26:40
 * @version 1.0.0
 */
public class MD5Utils {

    /**
     * 
     * @Description MD5加盐算法：md5(md5(pwd)+salt)
     * @param plainText 待加密值
     * @param salt 盐值
     * @return 算法加密后的hash值
     */
    public static String md5_salt(String plainText, String salt) {
        // 密码进行md5再加盐
        String temp = MD5Utils.md5(plainText) + salt;
        // 将加盐后的md5再进行md5
        return MD5Utils.md5(temp);
    }

    /**
     * 
     * @Description md5加密
     * @param plainText
     * @return MD5加密后的hash值
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        // 16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);
        // 如果生成数字未满32位，前要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }
    
    /**
     * 
     * @Description (获取随机盐值)
     * @return 16位盐值
     */
    public static String getRandomSalt() {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        return sb.toString();
    }
    
}
